const { WebSocketServer } = require('ws')
const http = require('http')
const { setupWSConnection } = require('y-websocket/bin/utils')

const host = process.env.HOST || 'localhost'
const port = process.env.PORT || 1234

const server = http.createServer((request, response) => {
  response.writeHead(200, { 'Content-Type': 'text/plain' })
  response.end('okay')
})

const wss = new WebSocketServer({ server })

wss.on('connection', (ws, request) => {
  console.log('New WebSocket connection')
  setupWSConnection(ws, request)
})

server.listen(port, host, () => {
  console.log(`WebSocket server running on ws://${host}:${port}`)
})

// 优雅关闭
process.on('SIGINT', () => {
  console.log('Shutting down WebSocket server...')
  server.close(() => {
    console.log('Server closed')
    process.exit(0)
  })
})
